#include <boost/interprocess/managed_shared_memory.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>

#include "common.h"

int main(int argc, char* argv[])
{
  namespace ip  = boost::interprocess;

  // Open Shared Memory Manager
  ip::managed_shared_memory msm(ip::open_only, MEMORY_NAME);

  // Open Shared Mat Header
  const auto shared_image_header
    = msm.find<SharedImageHeader>("MatHeader").first;

  // Make shared and read only (const) cv::Mat 
  // Header information (size and type) is also provided from Shared Memory
  const cv::Mat shared(
    shared_image_header->size,
    shared_image_header->type,
    msm.get_address_from_handle(shared_image_header->handle));
    
  // final_version of shared matrix
  int final_version = 0;

  while ('q' == cv::waitKey(1)) {
    // Spinning until shared image version is updated
    // or break if 'q' key is pressed.
    while (final_version == shared_image_header->version)
      if ('q' == cv::waitKey(10)) break;

    // Update Version and show image.
    final_version = shared_image_header->version;
    cv::imshow("Client Window", shared);
  }

  return 0;
}